import React, { useEffect, useRef, useState } from 'react'
import {
  Card,
  Button,
  Table,
  Pagination,
  Modal,
  Form,
  Input,
  Upload,
  message,
  FormInstance,
  Popconfirm,
} from 'antd'
import {
  PlusOutlined,
  FormOutlined,
  DeleteOutlined,
  LoadingOutlined,
} from '@ant-design/icons'
import {
  RecordItem,
  reqTrademarkList,
  reqaddTrademark,
  updataTradmarkl,
  deltrademarkItem,
} from '@/api/Product/trademark'
import type { RecordList } from '@/api/Product/trademark'
import type { ColumnsType } from 'antd/es/table'
import FormItem from 'antd/lib/form/FormItem'
import { RcFile } from 'antd/lib/upload'
import { UploadFile } from 'antd/lib/upload/interface'
function Trademark() {
  const [fileList, setFileList] = useState<UploadFile<any>[]>([])
  // message提示框
  // 定义分页列表请求参数
  const [listParameter, setListParameter] = useState({
    limit: 3,
    page: 1,
  })
  const [toTal, settoTal] = useState(0)
  // 加载
  const [loading, setLoading] = useState(false)
  // 新增弹出框的展示
  const [open, setOpen] = useState(false)
  // Form表单数据
  const [form] = Form.useForm()
  const userName = Form.useWatch('username', form)
  // const imageUrls = Form.useWatch('imageUrl', form)
  // 并不需要使用表单收集.因为表单收集到的是文件对象
  const [fromId, setFromId] = useState(-1)
  // upload数据
  const [imageUrl, setimageUrl] = useState('')
  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}></div>
    </div>
  )
  // 表格渲染数据
  const [dataSource, setDataSource] = useState<RecordList>([])
  //表格配置项
  const columns: ColumnsType<RecordItem> = [
    {
      title: '姓名',
      dataIndex: 'tmName',
      align: 'center',
    },
    {
      title: '年龄',
      dataIndex: 'logoUrl',
      align: 'center',
      render: (a: any, b: any, c: any) => {
        // a:当前值,b:row,c:index
        return (
          <div>
            <img width={100} src={a} alt="" />
          </div>
        )
      },
    },
    {
      title: '操作',
      render: (a: any, row: any, c: any) => {
        // 没有dataIndex a:row,b:row,c:index
        return (
          <div>
            <Button
              onClick={reSaveItem(row)}
              type="primary"
              shape="round"
              icon={<FormOutlined />}
            ></Button>
            <Popconfirm
              title="确认删除吗?"
              onConfirm={delItem(row)}
              okText="Yes"
              cancelText="No"
            >
              <Button
                style={{ marginLeft: 20 }}
                shape="round"
                type="primary"
                danger
                icon={<DeleteOutlined />}
              ></Button>
            </Popconfirm>
          </div>
        )
      },
    },
  ]
  // 定义分页列表请求函数
  const getTradeList = async function () {
    setLoading(true)
    let re = await reqTrademarkList(listParameter.page, listParameter.limit)
    setDataSource(re.records)
    settoTal(re.total)
    setLoading(false)
  }
  // 修改页码后的回调
  const onChange = function (page: number, limit: number) {
    setListParameter({
      page,
      limit,
    })
  }
  // 打开新增栏
  const openAdd = function () {
    //首先需要清除原有数据,保证数据为空
    setimageUrl('')
    form.setFieldsValue({
      username: '',
    })
    setFromId(-1)
    setOpen(true)
  }
  // 关闭新增栏
  const closeModel = function () {
    setOpen(false)
  }
  // 上传图片
  const beforeUpload = async function (file: RcFile) {
    return true
  }
  // 上传成功的回调
  const onChangeImg = function ({ file }: any) {
    // 设置展示地址
    setimageUrl(file.response?.data)
    // 由于使用使用upload时需要含有,需要修复fileList被穿透的value数据扰乱的bug,所以需要对list单独列出
    setFileList([
      {
        uid: file.uid,
        name: file.name,
        url: file.response?.data,
      },
    ])
  }
  // 点击确定新增品牌
  const onConfim = async function () {
    try {
      const bol = await form.validateFields()
      if (fromId !== -1) {
        await updataTradmarkl({
          logoUrl: imageUrl,
          tmName: userName,
          id: fromId,
        })
      } else {
        await reqaddTrademark({ logoUrl: imageUrl, tmName: userName })
      }
      message.success('新增成功')
      setOpen(false)
      //重新获取数据
      getTradeList()
    } catch (error) {
      console.log(error)
    }
  }
  //覆写
  const reSaveItem = function (row: RecordItem) {
    return async () => {
      setFromId(row.id)
      form.setFieldsValue({
        username: row.tmName,
        imageUrl: row.logoUrl,
      })
      setimageUrl(row.logoUrl)
      setOpen(true)
      // eff创建监听数据用于存储form的数据
      console.log(form.getFieldsValue())
    }
    // updataTradmarkl()
    // deltrademarkItem
  }
  //删除
  const delItem = function (row: RecordItem) {
    return async () => {
      await deltrademarkItem(row.id)
      //重新获取数据
      message.success('删除成功')
      getTradeList()
    }
  }
  useEffect(() => {
    getTradeList()
  }, [listParameter])
  return (
    <div>
      <Card bordered={false} style={{ margin: 30, marginBottom: -30 }}>
        <Button type="primary" icon={<PlusOutlined />} onClick={openAdd}>
          添加
        </Button>
      </Card>
      <Card hoverable style={{ margin: 30 }}>
        <Table
          loading={loading}
          rowKey={'id'}
          dataSource={dataSource}
          pagination={{ position: [] }}
          columns={columns}
          bordered
        ></Table>
        <Pagination
          showQuickJumper
          current={listParameter.page}
          pageSize={listParameter.limit}
          showSizeChanger
          pageSizeOptions={[3, 5, 7, 9]}
          total={toTal}
          onChange={onChange}
        />
        {/* 新增的提交表单 */}
        <Modal
          title="Title"
          visible={open}
          maskClosable={true}
          onCancel={closeModel}
          onOk={onConfim}
        >
          <Form form={form}>
            <FormItem
              label="品牌名称"
              name="username"
              rules={[{ required: true, message: '必须输入名字' }]}
            >
              {/* <Input onChange={saveName} /> */}
              <Input />
            </FormItem>
            <Form.Item
              label="品牌LOGO"
              rules={[{ required: true, message: '必须传入文件' }]}
            >
              {/* <Input.Password onChange={savePassword} /> */}

              <Upload
                listType="picture-card"
                maxCount={1}
                className="avatar-uploader"
                action={`/app-dev/admin/product/fileUpload`}
                beforeUpload={beforeUpload}
                showUploadList={false}
                onChange={onChangeImg}
                fileList={fileList}
              >
                {imageUrl ? (
                  <img src={imageUrl} alt="avatar" style={{ width: '100%' }} />
                ) : (
                  uploadButton
                )}
              </Upload>
            </Form.Item>
          </Form>
        </Modal>
      </Card>
    </div>
  )
}

export default Trademark
